#include "SelfInfoDialog.h"
#include <QFileDialog>
#include <QPushButton>
#include <QRegularExpression>
#include <QShortcut>
#include <QTimer>
#include <QVBoxLayout>
#include "../Model/Data.h"
#include "Style.h"
#include "Toast.h"

using namespace model;

////////////////////////////////////////////
/// 点击 left_widget 中的头像后显示的界面
////////////////////////////////////////////
SelfInfoDialog::SelfInfoDialog(QWidget* parent)
    : QDialog(parent)
{
    init_ui();
    connect_slot();
}

/// @brief 初始化UI
void SelfInfoDialog::init_ui()
{
    this->setWindowTitle("编辑资料");
    this->setFixedSize(420, 380);
    this->setWindowIcon(QIcon(":/image/logo.png"));
    this->setAttribute(Qt::WA_DeleteOnClose);
    /* 1. 头像 */
    avatar = new CircleButton();
    avatar->setFixedSize(70, 70);
#if TEST_UI
    avatar->setIcon(QIcon(":/image/defaultAvatar.png"));
#endif  // TEST_UI
    avatar->setIconSize(QSize(70, 70));
    /* 2.昵称 */
    const QString style =
        "QLineEdit {"
        "background-color: white;"
        "border: none;"
        "border-radius: 10px;"
        "font-size: 14px;"
        "padding-left: 15px;"
        "padding-right: 10px;"
        "}";
    nick_name = new PromptLineEdit();
    nick_name->setFixedSize(QSize(360, 40));
    nick_name->setStyleSheet(style);
    nick_name->setPromptText("昵称");
    nick_name->setMaxLength(36);
    /* 3.个性签名 */
    description = new PromptLineEdit();
    description->setFixedSize(QSize(360, 35));
    description->setStyleSheet(style);
    description->setPromptText("个签");
    description->setMaxLength(80);
    /* 3.手机号发送验证码按钮 */
    QWidget* phone_widget = new QWidget();
    phone_widget->setStyleSheet(
        "QPushButton {"
        "font-size: 14px;"
        "border-radius: 5px;"
        "}");
    QHBoxLayout* phone_layout = new QHBoxLayout();
    phone_layout->setContentsMargins(0, 0, 0, 0);
    phone_layout->setSpacing(20);
    phone_widget->setLayout(phone_layout);
    get_verify_btn = new QPushButton("获取验证码");
    get_verify_btn->setFixedSize(QSize(100, 35));
    // get_verify_btn->setStyleSheet(get_blue_button_style());
    static QString blue_style  = get_blue_button_style();
    blue_style                += "QPushButton:!enabled{ color:#000000; }";
    get_verify_btn->setStyleSheet(blue_style);
    phone_num = new PromptLineEdit();
    phone_num->setFixedSize(QSize(240, 35));
    phone_num->setStyleSheet(style);
    phone_num->setPromptText("电话");
    phone_num->setMaxLength(11);
    phone_layout->addWidget(phone_num);
    phone_layout->addWidget(get_verify_btn);
    /* 4. 保存和取消按钮 */
    QWidget* container = new QWidget();
    container->setStyleSheet(
        "QPushButton {"
        "font-size: 14px;"
        "border-radius: 5px;"
        "}");
    QHBoxLayout* h_layout = new QHBoxLayout();
    h_layout->setContentsMargins(0, 0, 20, 0);
    h_layout->setSpacing(10);
    container->setLayout(h_layout);
    const QSize b_size = QSize(80, 35);
    save               = new QPushButton();
    save->setFixedSize(b_size);
    save->setText("保存");
    save->setStyleSheet(blue_style);
    cancel = new QPushButton();
    cancel->setFixedSize(b_size);
    cancel->setText("取消");
    cancel->setStyleSheet(get_white_button_style());
    h_layout->addWidget(save, 0, Qt::AlignRight);
    h_layout->addWidget(cancel, 0, Qt::AlignRight);
    /* 补充, 添加ID */
    id = new PromptLineEdit();
    id->setFixedSize(QSize(360, 35));
    id->setStyleSheet(style);
    id->setPromptText("QQ号");
    id->setMaxLength(11);
    id->setDisabled(true);
    /* 5. 添加到布局当中 */
    QVBoxLayout* v_layout = new QVBoxLayout();
    v_layout->setContentsMargins(0, 0, 0, 0);
    v_layout->setSpacing(20);
    this->setLayout(v_layout);
    v_layout->addWidget(avatar, 0, Qt::AlignHCenter);
    v_layout->addWidget(id, 0, Qt::AlignHCenter);
    v_layout->addWidget(nick_name, 0, Qt::AlignHCenter);
    v_layout->addWidget(description, 0, Qt::AlignHCenter);
    v_layout->addWidget(phone_widget, 0, Qt::AlignHCenter);
    v_layout->addWidget(container, 0, Qt::AlignRight);
    /* 获得DataCenter */
    data_center = DataCenter::get_instance();
}

/// @brief 连接信号槽
void SelfInfoDialog::connect_slot()
{
    /* 设置初始的个人信息(如果本地没有就从网络中获取) */
    if (data_center->get_cur_user_info() == nullptr) {
        connect(data_center, &DataCenter::get_myself_info_done, this, &SelfInfoDialog::set_myself_info, Qt::SingleShotConnection);
        data_center->get_myself_info_async();
    } else {
        set_myself_info();
    }
    /* 点击保存按钮 */
    connect(save, &QPushButton::clicked, this, &SelfInfoDialog::handle_save_btn_clicked);
    /* 点击取消按钮 */
    connect(cancel, &QPushButton::clicked, this, &SelfInfoDialog::close);
    /* 让敲击回车和点击保存有同样的效果 */
    QShortcut* enter_shortcut  = new QShortcut(QKeySequence(Qt::Key_Return), this);  // 小键盘的回车键
    QShortcut* return_shortcut = new QShortcut(QKeySequence(Qt::Key_Enter), this);   // 主键盘的回车键
    connect(enter_shortcut, &QShortcut::activated, this, &SelfInfoDialog::handle_save_btn_clicked);
    connect(return_shortcut, &QShortcut::activated, this, &SelfInfoDialog::handle_save_btn_clicked);
    /* 让按ESC和点击取消按钮有同样的效果 */
    QShortcut* esc_shortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this);
    connect(esc_shortcut, &QShortcut::activated, this, &SelfInfoDialog::close);
    /* 点击获取验证码按钮 */
    connect(get_verify_btn, &QPushButton::clicked, this, &SelfInfoDialog::handle_get_verify_btn_clicked);
    /* 点击头像 */
    connect(avatar, &CircleButton::clicked, this, &SelfInfoDialog::handle_avatar_clicked);
    /* 头像修改完成后立即更改 */
    connect(data_center, &DataCenter::set_cur_user_info_avatar_done, this, &SelfInfoDialog::avatar_change_done);
}

/// @brief 设置当前界面的个人信息
void SelfInfoDialog::set_myself_info()
{
    UserInfo* user_info = data_center->get_cur_user_info();
    this->id->setText(user_info->user_id);
    this->avatar->setIcon(user_info->avatar);
    this->nick_name->setText(user_info->nick_name);
    this->description->setText(user_info->description);
    this->phone_num->setText(user_info->phone_num);
    phone_num_txt = user_info->phone_num;
}

/// @brief 设置保存按钮点击事件, 向服务端发送请求. 成功了会设置DataCenter中的cur_user_info
void SelfInfoDialog::handle_save_btn_clicked()
{
    /* 检查合法性 */
    if (nick_name->text().trimmed().isEmpty() ||
        description->text().trimmed().isEmpty() ||
        phone_num->text().trimmed().isEmpty()) {
        Toast::showMessage("请填写完整信息!!");
    }
    data_center->set_user_nick_name_async(nick_name->text());
    data_center->set_user_description_async(description->text());
    QString phone_verify_code    = phone_num->text();
    QString phone_verify_code_id = data_center->get_phone_verify_code_id();
    data_center->set_user_phone_num_async(phone_num_txt, phone_verify_code_id, phone_verify_code);
    /* 关闭窗口 */
    this->close();
}

/// @brief 向服务器发送获取验证码请求
void SelfInfoDialog::handle_get_verify_btn_clicked()
{
    /* 检查合法性 */
    const QString cur_phone_num_text = phone_num->text();
    if (cur_phone_num_text.trimmed().isEmpty()) {
        Toast::showMessage("手机号为空!!");
        return;
    }
    QRegularExpression phoneRegex("^1[3-9]\\d{9}$");
    if (!phoneRegex.match(cur_phone_num_text).hasMatch()) {
        Toast::showMessage("手机号格式不正确!!");
        return;
    }
    if (cur_phone_num_text == phone_num_txt) {
        Toast::showMessage("手机号未改变!!");
        return;
    }
    /* 每过60s只能发送1次验证码 */
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, [=]() {
        get_verify_btn->setText(QString::number(time_cnt) + "s");
        get_verify_btn->setEnabled(false);
        time_cnt--;
        if (time_cnt <= 0) {
            get_verify_btn->setText("获取验证码");
            get_verify_btn->setEnabled(true);
            time_cnt = 60;
            timer->stop();
            timer->deleteLater();
        }
    });
    get_verify_btn->setEnabled(false);
    timer->start(1000);
    this->phone_num_txt = cur_phone_num_text;
    /* 发送请求 */
    data_center->get_phone_verify_code_async(this->phone_num_txt);
    /* 把前面的手机号换成验证码 */
    phone_num->setPromptText("验证码");
    phone_num->clear();
}

/// @brief 向服务器发送更换头像请求
void SelfInfoDialog::handle_avatar_clicked()
{
    /* 弹出文件选择对话框 */
    QString file_path = QFileDialog::getOpenFileName(this, "选择图片", QDir::currentPath(), "*.png *.jpg *.jpeg");
    if (file_path.isEmpty()) {
        Toast::showMessage("未选择任何图片!!");
        return;
    }
    /* 读取图片内容 */
    QByteArray image_data = read_file(file_path);
    if (image_data.isEmpty()) {
        Toast::showMessage("图片读取失败!!");
        return;
    }
    /* 发送请求 */
    data_center->set_user_avatar_async(image_data);
}

/// @brief 个人头像修改成功
void SelfInfoDialog::avatar_change_done()
{
    UserInfo* user_info = data_center->get_cur_user_info();
    avatar->setIcon(user_info->avatar);
}
